
import React from 'react'

export default {
    state:{
        list:[ 
        //     {name:"橘子",price:5,checked:false,num:1,id:0},
        // {name:"西瓜",price:7,checked:false,num:1,id:1},
        // {name:"苹果",price:10,checked:false,num:1,id:2},
        // {name:"枇杷",price:15,checked:false,num:1,id:3},
    ]
    },

    //同步的
    reducers:{
        setList(state:any,action:any){
            return {
                ...state,
                list:action.payload,
            }
        },


        checkinput(state:any,action:any){
            const id=action.payload
            for (const item of state.list) {
                if(item.id==id){
                    item.checked=!item.checked
                    break
                }
            }
            return {
                ...state,
                list: [...state.list]
            }
        },

        changeNum(state: any, action: any) {
            const { id, n } = action.payload;
            for (const item of state.list) {
                if (item.id === id) {
                    item.num += n;
                    break;
                }
            }
            return {
                ...state,
                list: [...state.list]
            }
        },
        del(state:any,action:any){
            const id = action.payload;
            state.list = state.list.filter((item:any)=>item.id !== id);
            return {
                ...state,
            }
        }
    },

    effects:{
        *getData({payload}:any,{call,put}:any){
            yield delay(2000);//延迟两秒钟
            const list = [
                {name:"橘子",price:5,checked:false,num:1,id:0},
        {name:"西瓜",price:7,checked:false,num:1,id:1},
        {name:"苹果",price:10,checked:false,num:1,id:2},
        {name:"枇杷",price:15,checked:false,num:1,id:3},
            ]
            //这里的put就是dispatch
            //把数据存入state
            yield put({
                type:"setList",
                payload:list,
            })

        }
        // *getData({payload}:any,{call,put}:any){
        //    const list =  yield call(getCartDatApi);//延迟两秒钟
        //    console.log('res',list);
        //     //这里的put就是dispatch
        //     //把数据存入state
        //     yield put({
        //         type:"setList",
        //         payload:list,
        //     })

        // }
    }
   
 
}

function delay(wait:number){
    return new Promise<void>((resolve,reject)=>{
        setTimeout(()=>{
            resolve();
        },wait);
    });
}



